package cc.ufinity.networkdiagnose.service;
 
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.util.HttpUtils;
import cc.ufinity.networkdiagnose.util.StringUtils;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

import java.io.InputStream;
import java.util.List;

import cc.ufinity.networkdiagnose.view.HomePageActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import cc.ufinity.networkdiagnose.view.R;
import cc.ufinity.networkdiagnose.widget.MyMobileCfgWidget;
import android.os.Handler;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import cc.ufinity.networkdiagnose.manager.TaskParser;

import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.database.SQLException;


public class TaskService extends Service {
	final static String TAG = "TaskService";
	private String myPhoneNumber; 
	private final int PERIODIC_EVENT_TIMEOUT = 1000 * 60*5;
	private Handler mPeriodicEventHandler;
	private TaskParser taskParser;
	private List<Task> currentTasks = null; 

	// 通知管理器
	private NotificationManager nm;
	// 通知显示内容
	private PendingIntent pd;
	//private int Notification_ID_BASE = 110;
	private Notification baseNF;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		Log.d("TaskService", "onCreate");
		super.onCreate();
//		if (!isAppRunning()) {		
//			if(checkTask()){
//			 notification();
//			}
//		}
		mPeriodicEventHandler = new Handler();
		mPeriodicEventHandler.postDelayed(doPeriodicTask,
				PERIODIC_EVENT_TIMEOUT);

	}

	private Runnable doPeriodicTask = new Runnable() {
		public void run() {
			// your action here
			new Thread(){
				public void run() {					
					if (!isAppRunning()) {		
						if(checkTask()){
						 notification();
						}
					}
				}
			}.start();
			
			mPeriodicEventHandler.postDelayed(doPeriodicTask,
					PERIODIC_EVENT_TIMEOUT);
		}
	};

	public void onStart(Intent intent, int startId) {
		// intent.
		Log.e(TAG, "TaskService started.....");
		super.onStart(intent, startId);
	}

	 protected void notification(){
		 
	    	nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	    	Intent intent = new Intent(this,HomePageActivity.class);  
	    	intent.putExtra("intentFlag", "taskService");
	        pd = PendingIntent.getActivity(this, 0, intent, 0); 
	    	//BASE Notification ID  
	   
	    	//新建状态栏通知  
	        baseNF = new Notification();  
	           
	        //设置通知在状态栏显示的图标  
	        baseNF.icon = R.drawable.home;  
	          
	        //通知时在状态栏显示的内容  
	        baseNF.tickerText = "人人都是测试员：有新测试任务下达!";  
	          
	        //通知的默认参数 DEFAULT_SOUND, DEFAULT_VIBRATE, DEFAULT_LIGHTS.   
	        //如果要全部采用默认值, 用 DEFAULT_ALL.  
	        //此处采用默认声音  
	        baseNF.defaults |= Notification.DEFAULT_SOUND;  
	        baseNF.defaults |= Notification.DEFAULT_VIBRATE;  
	      //  baseNF.defaults |= Notification.DEFAULT_LIGHTS;  
	          
	        //让声音、振动无限循环，直到用户响应  
	      //  baseNF.flags |= Notification.FLAG_INSISTENT;  
	          
	        //通知被点击后，自动消失  
	        baseNF.flags |= Notification.FLAG_AUTO_CANCEL;  
	          
	        //点击'Clear'时，不清楚该通知(QQ的通知无法清除，就是用的这个)  
	     //   baseNF.flags |= Notification.FLAG_NO_CLEAR;  
	          
	          
	        //第二个参数 ：下拉状态栏时显示的消息标题 expanded message title  
	        //第三个参数：下拉状态栏时显示的消息内容 expanded message text  
	        //第四个参数：点击该通知时执行页面跳转  
	        baseNF.setLatestEventInfo(this, "人人都是测试员", "测试提醒：有新任务下达！", pd);  
	          
	        //发出状态栏通知  
	        //The first parameter is the unique ID for the Notification   
	        // and the second is the Notification object.       
	    	   nm.notify(0, baseNF);  
	    }
//判断应用程序是否在前台运行
	 protected boolean isAppRunning() {
		 String packageName = "cc.ufinity.networkdiagnose.view";
			ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
		    List<RunningTaskInfo>  tasksInfo = am.getRunningTasks(1);  
		    if(tasksInfo.size() > 0){  
	            System.out.println("---------------包名-----------"+tasksInfo.get(0).topActivity.getPackageName());
	            //应用程序位于堆栈的顶层  
	            if(packageName.equals(tasksInfo.get(0).topActivity.getPackageName())){  
	                return true;  
	            }  
	        }  
	        return false;
	}
	//检查是否有新任务 
	
	protected  void updateTasks(List<Task> currentTasks) {
		 //打开或创建test.db数据库  
		SQLiteDatabase db ;
        db = openOrCreateDatabase("preTasks.db", Context.MODE_PRIVATE, null); 
        try {
            db.execSQL("DELETE FROM tasks where 1=1");}
        catch (Exception e) {
			// TODO: handle exception
        	System.err.println("数据库删除错误！---------------------"+e);
		}
        try{
    		for(Task curTask : currentTasks){
    	        //插入数据  
    			String sql = "INSERT INTO tasks(taskid) VALUES('" + curTask.id+ "')";
    	        db.execSQL(sql);  
    		}	 
		} catch (Exception e) {
			// TODO: handle exceptionsy
			System.err.println("数据库插入数据错误！---------------------"+e);
		}
		db.close();  //关闭当前数据库  
       
	}

	protected boolean isExit( String taskId){
		 //打开或创建test.db数据库  
       SQLiteDatabase db = openOrCreateDatabase("preTasks.db", Context.MODE_PRIVATE, null);  
       Cursor myCursor = db.query("tasks", null, "taskid=?", new String[]{taskId}, null, null, null);
       boolean isExitItem = false;
		try {
			//String sql = "select * from tasks where"
			myCursor = db.query("tasks", null, "taskid=?", new String[]{taskId}, null, null, null);

			if(myCursor.getCount() < 1)isExitItem = false;
			else {
				isExitItem =true;
			}
		} catch (SQLException e) {
			isExitItem = false;
			System.err.println("数据库查询错误！---------------------"+e);
		}
		db.close();
		myCursor.close();
		return isExitItem;
	}

	protected boolean checkTask() {
		taskParser = new PullTaskParser();
		//String url = "http://221.130.165.252/Task/ReturnXML.aspx";
		String url = R.string.server_url + "/Task/ReturnXML.aspx";
		Log.d("Task", "my phone number is:" + myPhoneNumber);
		myPhoneNumber = TelManager.testPhone;
		if (StringUtils.isEmpty(myPhoneNumber)) {
            SharedPreferences settings = getApplicationContext().getSharedPreferences(MyMobileCfgWidget.PREFS_NAME, 0);
            myPhoneNumber = settings.getString(MyMobileCfgWidget.PREFS_KEY, "");
        }
		String requrl = url + "?TaskPhone=" + myPhoneNumber;
		try {
			InputStream is = HttpUtils.getInputStream(requrl);
			currentTasks = taskParser.parse(is);
			if(currentTasks == null || currentTasks.isEmpty())return false;
		} catch (Exception e) {
			Log.e(TAG, "解析XML任务时出错：", e);
			return false;
		}	
		//currentTasks = getTasks();
         for(Task task : currentTasks){
        	 if( !isExit(task.id) ){
        		 updateTasks(currentTasks);
        		 return true;
        	 }
        }
         return false;
	}

}
